﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using Skyworth.CRM.Common;
using Skyworth.CRM.Service.Entity;
using Skyworth.CRM.Service.IBLL;

namespace Skyworth.CRM.Web.Orders
{
    public partial class EmpAddOrder : BasePage
    {
        protected int CustId = 0;
        protected int OrderId = 0;
        protected int EmpdId = 0;
        private static IOrdersBLL ordersBLL = IocContainer.Instance.Resolve<IOrdersBLL>();
        protected static ICustCashBLL CustCashBll = IocContainer.Instance.Resolve<ICustCashBLL>();
        private static ICustContactBLL custContactBLL = IocContainer.Instance.Resolve<ICustContactBLL>();
        private static ICustDreeBLL dreeBll = IocContainer.Instance.Resolve<ICustDreeBLL>();
        private static IStockBLL stockBLL = IocContainer.Instance.Resolve<IStockBLL>();
        private IBrandBLL brandBLL = IocContainer.Instance.Resolve<IBrandBLL>();
        private static IProductBLL productBLL = IocContainer.Instance.Resolve<IProductBLL>();
        protected void Page_Load(object sender, EventArgs e)
        {
            CustId = IndividualId;
            EmpdId = IndividualId;
            if (!IsPostBack)
            {
               // string strCustId = Request.QueryString["custId"];
                if ("update" == Request.QueryString["Type"].ToString().ToLower())
                {
                    int.TryParse(Request.QueryString["Id"], out OrderId);

                    if (OrderId > 0)
                    {
                        DataTable orderDetail;
                        Order ordeEntity = ordersBLL.GetOrderById(OrderId, out orderDetail);
                        this.txtOrderName.Text = ordeEntity.OrderName;
                        this.txtDescription.Text = ordeEntity.Notes;
                        CustId = ordeEntity.CustId;
                        BuildDropDownList(CustId);
                        //if (string.IsNullOrEmpty(strCustId)){
                            this.ddlAddress.SelectedValue = ordeEntity.CusDreeId.ToString();
                            this.ddlLinkPeople.SelectedValue = ordeEntity.ContactId.ToString();
                            this.ddlStock.SelectedValue = ordeEntity.StockId.ToString();
                        //}
                        this.txtOrderNo.Text = ordeEntity.OrderCode;
                        this.orderDetailBody.Text = BuildOrderDetail(orderDetail);
                        this.txtTotalNumber.Text = ordeEntity.TotalNumber.ToString();
                        this.txtTotalVolume.Text = ordeEntity.TotalVolume.ToString();
                        this.txtTotalPrice.Text = ordeEntity.TotalPrice.ToString();
                        this.txtTotalTaxPrice.Text = ordeEntity.TotalTaxPrice.ToString();
                       
                        this.txtCustId.Value = ordeEntity.CustId.ToString();
                        this.txtCustomerName.Text = ordeEntity.CustomerName;
                    }
                }
                else
                {
                    this.txtOrderNo.Text = "CSEO" + DateTime.Now.ToString("yyyyMMddHHmmss");
                }
                 
                BinDropDownList(this.ddlBrand, brandBLL.GetBrand("", null), "【请选择品牌】", "-1");
               

                //CustCash cash = CustCashBll.GetCustomerCash(CustId);
                //if (cash != null)
                //{
                //    this.txtTotalMoney.Text = cash.TotalAmount.ToString();
                //    this.txtCredit.Text = cash.CreditAmount.ToString();
                //    this.txtCashAmount.Text = cash.CashAmount.ToString();
                //}
            }
        }


        private void BuildDropDownList(int custId)
        {
            DataTable dtContact = custContactBLL.Query(" FCustId=" + custId);
            BinDropDownList(this.ddlLinkPeople, dtContact, "", "");

            DataTable dtAddress = dreeBll.Query(" FCustId=" + custId);
            BinDropDownList(this.ddlAddress, dtAddress, "", "");

            DataTable dtStock = stockBLL.Query(" and FDeptId=" + custId + " and Ftype=1");
            BinDropDownList(this.ddlStock, dtStock, "", "");

        }


        [WebMethod]
        public static string GetCustContact(int custId)
        {
            DataTable dtContact = custContactBLL.Query(" FCustId=" + custId);
            string strResult = SerializationHelper.DataTable2Json(dtContact);
            return strResult;
        }

        [WebMethod]
        public static string GetCustAddress(int custId)
        {
            DataTable dtAddress = dreeBll.Query(" FCustId=" + custId);
            string strResult = SerializationHelper.DataTable2Json(dtAddress);
            return strResult;
        }

        [WebMethod]
        public static string GetCustStock(int custId)
        {
            DataTable dtStock = stockBLL.Query(" and FDeptId=" + custId + " and Ftype=1");
            string strResult = SerializationHelper.DataTable2Json(dtStock);
            return strResult;
        }
        [WebMethod]
        public static CustCash GetCustCash(int custId)
        {
            CustCash cash = CustCashBll.GetCustomerCash(custId);
           // cash = new CustCash();
            return cash;
        }

        protected string BuildOrderDetail(DataTable orderDetail)
        {
            StringBuilder result = new StringBuilder();
            if (orderDetail != null && orderDetail.Rows.Count > 0)
            {
                foreach (DataRow row in orderDetail.Rows)
                {
                    result.Append("<tr>");
                    result.AppendFormat("<td>{0}</td>", row["FProductName"]);
                    result.AppendFormat("<td>{0}</td>", row["Fqty"]);
                    result.AppendFormat("<td>{0}</td>", row["Famount"]);
                    result.AppendFormat("<td>{0}</td>", row["Ftaxamount"]);
                    result.Append("<td><a href='javascript:void(0)' onclick='RemoveRow(this)'>移除</a></td>");
                    result.AppendFormat("<td style='display: none;'>{0}</td>", row["FUnitVolume"]);
                    result.AppendFormat("<td style='display: none;'>{0}</td>", row["Fprice"]);
                    result.AppendFormat("<td style='display: none;'>{0}</td>", row["Ftax"]);
                    result.AppendFormat("<td style='display: none;'>{0}</td>", row["Ftaxprice"]);
                    result.AppendFormat("<td style='display: none;'>{0}</td>", row["Ffanli"]);
                    result.AppendFormat("<td style='display: none;'>{0}</td>", row["Funit"]);
                    result.AppendFormat("<td style='display: none;'>{0}</td>", row["Fqtyvolume"]);
                    result.AppendFormat("<td style='display: none;'>{0}</td>", row["Fnote"]);
                    result.AppendFormat("<td style='display: none;'>{0}</td>", row["FProductId"]);
                    result.Append("</tr>");
                }
            }

            return result.ToString();
        }

        [WebMethod]
        public static string CreateOrder(string orderName, string orderNo, int custId, int empId, int dreeId, int stockId, int contactId, double totalNumber, double totalVolume, decimal totalPrice, decimal totalTaxPrice, string notes, string json, Boolean isSubmit)
        {
            Order model = new Order();
            model.OrderName = orderName;
            model.ContactId = contactId;
            model.CustId = custId;
            model.CusDreeId = dreeId;
            model.StockId = stockId;
            model.Notes = notes;
            model.TotalPrice = totalPrice;
            model.TotalNumber = totalNumber;
            model.TotalVolume = totalVolume;
            model.TotalTaxPrice = totalTaxPrice;
            model.Creator = empId;
            model.OrderCode = orderNo;

            DataTable dt = SerializationHelper.Json2DataTable(json);

            return ordersBLL.AddOrder(model, dt, isSubmit);
        }

        [WebMethod]
        public static Boolean UpdateOrder(int orderId, string orderName, string orderNo, int custId, int empId, int dreeId, int stockId, int contactId, double totalNumber, double totalVolume, decimal totalPrice, decimal totalTaxPrice, string notes, string json, Boolean isSubmit)
        {
            Order model = new Order();
            model.OrderName = orderName;
            model.ContactId = contactId;
            model.CustId = custId;
            model.CusDreeId = dreeId;
            model.StockId = stockId;
            model.Notes = notes;
            model.TotalPrice = totalPrice;
            model.TotalNumber = totalNumber;
            model.TotalVolume = totalVolume;
            model.TotalTaxPrice = totalTaxPrice;
            model.Creator = empId;
            model.Id = orderId;
            model.OrderCode = orderNo;

            DataTable dt = SerializationHelper.Json2DataTable(json);

            return ordersBLL.UpdateOrder(model, dt, isSubmit);
        }

        [WebMethod]
        public static string GetProductsWithPrice(string productName, string brandId, string productTypeId, string orderField, string orderValue, int pageIndex, int pagePerSize, string custId)
        {
            string strResult;
            IProductBLL productBLL = IocContainer.Instance.Resolve<IProductBLL>();
            StringBuilder strWhere = new StringBuilder(" where 1=1");
            if (!string.IsNullOrEmpty(productName))
            {
                strWhere.Append(" and ProductName like '%" + productName + "%'");
            }
            if (brandId != "-1")
            {
                strWhere.Append(" and brandId=" + brandId);
            }
            if (productTypeId != "-1")
            {
                strWhere.Append(" and ProductTypeId=" + productTypeId);
            }

            StringBuilder strOrderBy = new StringBuilder(" Order by ");
            strOrderBy.Append(!string.IsNullOrEmpty(orderField) ? " " + orderField : "  ProductName  ");
            strOrderBy.Append(!string.IsNullOrEmpty(orderValue) ? " " + orderValue : "  asc ");

            int totalRecords = 0;
            int totalPages = 0;
            if (string.IsNullOrEmpty(custId))
                custId = "0";
            DataTable dtProducts = productBLL.GetProductsWithPriceByPage(strWhere.ToString(), custId, strOrderBy.ToString(), pageIndex, pagePerSize, out totalRecords,
                                           out totalPages);

            strResult = SerializationHelper.DataTable2Json(dtProducts);

            return "{\"totalRecords\":\"" + totalRecords.ToString() + "\" ,\"totalPages\":\"" + totalPages.ToString() + "\",\"rows\":" +
                   strResult + " }";

        }

    }
}
